package com.unicom.auth.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.unicom.auth.controller.base.BaseController;
import com.unicom.auth.controller.dto.MyAppJSON;
import com.unicom.auth.controller.dto.TreeNode;
import com.unicom.auth.model.Org;
import com.unicom.auth.model.Role;
import com.unicom.auth.model.User;

public class OrgController extends BaseController {

	@Override
	public void index() {
		MyAppJSON<Org> appJSON = new MyAppJSON<Org>();
		List<Org> orgs = Org.dao.findAllWithLevel();
		appJSON.addItems(orgs);
		renderJson(appJSON);
	}

	public void show(){
		String code=getPara(0);
		MyAppJSON<Org> appJSON=new MyAppJSON<Org>();
		Org org=Org.dao.findById(code);
		appJSON.addItem(org);
		renderJson(appJSON);
	}
	public void update(){
		Org org=getModel(Org.class);
		MyAppJSON<Org> appJSON = new MyAppJSON<Org>();
		if(org.update()){
			forwardAction("/backend/org/tree");
		}else{
			appJSON.setErrCode(MyAppJSON.ERR_UPDATE);
			appJSON.setMessage("更新失败");
			renderJson(appJSON);
		}
	}
	public void save(){
		Org org=getModel(Org.class);
		MyAppJSON<Org> appJSON = new MyAppJSON<Org>();
		if(org.save()){
			forwardAction("/backend/org/tree");
		}else{
			appJSON.setErrCode(MyAppJSON.ERR_CREATE);
			appJSON.setMessage("创建失败");
			renderJson(appJSON);
		}
	}
	public void tree() {
		MyAppJSON<TreeNode> appJSON = new MyAppJSON<TreeNode>();
		List<Org> orgs = Org.dao.findAll();
		Org rootOrg = Org.dao.getRootOrg();
		List<TreeNode> pNodes = new ArrayList<TreeNode>();
		pNodes.add(getTreeNode(rootOrg));
		Map<String, Org> orgMap = Org.dao.getOrgMap(orgs);
		Map<String, String> relationMap = Org.dao.getRelationMap(orgs);
		List<TreeNode> treeNodes = mountSubNodes(pNodes, orgMap, relationMap);
		for (TreeNode treeNode : treeNodes) {
			System.out.println(treeNode.getText() + "  "
					+ treeNode.getNodes().size());
			System.out.println("||||||||||");
			for (TreeNode t2 : treeNode.getNodes()) {
				System.out.println(t2.getText() + "  " + t2.getNodes().size());
			}
			System.out.println("||||||||||");
		}
		appJSON.addItems(treeNodes);
		renderJson(appJSON);
	}


	private List<TreeNode> mountSubNodes(List<TreeNode> pNodes,
			Map<String, Org> orgMap, Map<String, String> relationMap) {
		for (TreeNode pNode : pNodes) {
			List<TreeNode> treeNodes = new ArrayList<TreeNode>();
			for (Map.Entry<String, String> entry : relationMap.entrySet()) {
				if (pNode.getTags()[0].equals(entry.getValue())) {
					treeNodes.add(getTreeNode(orgMap.get(entry.getKey())));
				}
			}
			if (treeNodes.size() > 0) {
				mountSubNodes(treeNodes, orgMap, relationMap);
			}
			pNode.setNodes(treeNodes);
		}

		return pNodes;
	}

	private TreeNode getTreeNode(Org org) {
		TreeNode node = new TreeNode();
		node.setTags(org.getCode());
		node.setText(org.getName());
		return node;
	}
}
